package com.cloud.alibaba.oauthserver.service;


import com.cloud.alibaba.oauthserver.entity.dos.Permission;
import com.cloud.alibaba.oauthserver.mapper.PermissionMapper;
import com.cloud.alibaba.oauthserver.mapper.PermissionRoleMapper;
import com.cloud.alibaba.oauthserver.mapper.UserDao;
import com.cloud.alibaba.oauthserver.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * created by wuquan at 05/19/2021
 * ^_^ ^_^
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("======================================");
        Example example = new Example(com.cloud.alibaba.oauthserver.entity.dos.User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        com.cloud.alibaba.oauthserver.entity.dos.User user = userDao.selectOneByExample(example);
        if (user == null) {
            return null;
        }

        Integer userId = user.getId();
        List<Permission> permissions = permissionMapper.selectPermissions(userId);
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Permission permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission.getName()));
        }

        return User.withUsername(user.getUsername()).password(user.getPassword()).authorities(authorities).build();
    }
}
